#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>

#include "../../common/include/filesystem.h"
#include "../include/general.h"
#include "../include/common.h"

int fatal (char * msg)
{
    printf("%s -- \n", msg);
    return -1;
}

int
getLine (char * line, int linelen, FILE * stream)
{
    int i=0, c;
    for (i=0;i<linelen;i++)
        line[i] = 0;
    i=0;
    while(i<linelen){
        c=fgetc(stream);
        if(c==EOF)
                return -1;

        if(c=='\n')
                return 1;

        line[i]=c;
        i++;
    }

    if (i >= linelen)
        {
            BORRA_BUFFER;
        return 0;
        }
    return 0;
}

unsigned int
getFileSize(const char * file_name)
{
    struct stat statbuf;

    if( stat(file_name,&statbuf) == -1)
        return -1;

    return (statbuf.st_size);
}


void catchAlarm(int sig)
{
    return;
}

ssize_t
writeWithTimeout(int fd, const void *buf, size_t count, unsigned int timeout)
{
    int ret;
    static struct sigaction act, oact;

    act.sa_handler = catchAlarm;
    sigaction(SIGALRM, &act, &oact);

    alarm(timeout);

    ret = write(fd, buf, count);

    alarm(0);

    sigaction(SIGALRM, &oact, NULL);

    if (ret != count)
        return -1;
    else
        return ret;
}

ssize_t
readWithTimeout(int fd, void *buf, size_t count, unsigned int timeout)
{
    int ret;
    static struct sigaction act, oact;

    act.sa_handler = catchAlarm;
    sigaction(SIGALRM, &act, &oact);

    alarm(timeout);

    ret = read(fd, buf, count);

    alarm(0);

    sigaction(SIGALRM, &oact, NULL);

    if (ret != count)
        return -1;
    else
        return ret;
}

void clrtext(char * text, int len)
{
    while(len--)
    {
        text[len-1] = 0;
    }
    return;
}
